import 'package:flutter/material.dart';

import 'package:flutter_gen/gen_l10n/app_localizations.dart';

import '../../../core/auth/user_manager.dart';
import '../../../route/route_utils.dart';
import '../../../route/routes.dart';

class SecuritySettingsPage extends StatefulWidget {
  const SecuritySettingsPage({super.key});

  @override
  State<SecuritySettingsPage> createState() => _SecuritySettingsPageState();
}

class _SecuritySettingsPageState extends State<SecuritySettingsPage>
    with SingleTickerProviderStateMixin {
  bool _twoFactorEnabled = true;
  bool? _biometricLockEnabled = false;

  @override
  void initState() {
    super.initState();
    // 初始化状态
    UserManager().isBiometricLockEnabled().then((enabled) {
      setState(() {
        _biometricLockEnabled = enabled;
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    final l10n = AppLocalizations.of(context)!;

    return Scaffold(
      appBar: AppBar(title: Text(l10n.settingsSecurity)),
      body: ListView(
        padding: const EdgeInsets.all(16),
        children: [
          _buildCard(
            context,
            icon: Icons.lock_outline,
            title: l10n.securitySettingsChangePassword,
            subtitle: l10n.securitySettingsPasswordTip,
            onTap: () =>
                RouteUtils.pushForNamed(context, RoutePath.changePassword),
          ),
          _buildCard(
            context,
            icon: Icons.assignment_ind,
            title: l10n.securitySettingsSignature,
            subtitle: l10n.securitySettingsSignatureTip,
            onTap: () => RouteUtils.pushForNamed(context, RoutePath.signature),
          ),
          _buildCard(
            context,
            icon: Icons.phone_android,
            title: l10n.securitySettingsBindPhone,
            subtitle: l10n.securitySettingsBindPhoneTip,
            onTap: () => RouteUtils.pushForNamed(context, RoutePath.bindPhone),
          ),
          // 生物识别登录开关
          _buildSwitchCard(
            context,
            icon: Icons.fingerprint,
            title: l10n.securitySettingsBiometricAuth,
            subtitle: l10n.securitySettingsBiometricAuthTip,
            value: _biometricLockEnabled!,
            onChanged: (bool enabled) {
              setState(() {
                _biometricLockEnabled = enabled;
                UserManager().setBiometricLockEnabled(enabled);
              });
              ScaffoldMessenger.of(context).showSnackBar(
                SnackBar(
                    content: Text(enabled
                        ? l10n.securitySettingsBiometricOn
                        : l10n.securitySettingsBiometricOff)),
              );
            },
          ),

          _buildSwitchCard(
            context,
            icon: Icons.verified_user_outlined,
            title: l10n.securitySettingsTwoFactorAuth,
            subtitle: l10n.securitySettingsTwoFactorAuthTip,
            value: _twoFactorEnabled,
            onChanged: (bool enabled) {
              setState(() => _twoFactorEnabled = enabled);
              ScaffoldMessenger.of(context).showSnackBar(
                SnackBar(
                    content: Text(enabled
                        ? l10n.securitySettingsTwoFactorOn
                        : l10n.securitySettingsTwoFactorOff)),
              );
            },
          ),
          _buildCard(
            context,
            icon: Icons.devices_other,
            title: l10n.securitySettingsLoggedInDevices,
            subtitle: l10n.securitySettingsManageDevices,
            onTap: () => RouteUtils.pushForNamed(context, RoutePath.devices),
          ),
          const SizedBox(height: 20),
          _buildDangerCard(
            context,
            icon: Icons.delete_forever,
            title: l10n.securitySettingsDeleteAccountConfirmTitle,
            subtitle: l10n.securitySettingsDeleteAccountConfirmMsg,
            onTap: () => _confirmDeleteAccount(context),
          ),
        ],
      ),
    );
  }

  // 普通卡片
  Widget _buildCard(
    BuildContext context, {
    required IconData icon,
    required String title,
    required String subtitle,
    required VoidCallback onTap,
  }) {
    return Card(
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
      elevation: 1,
      margin: const EdgeInsets.only(bottom: 12),
      child: ListTile(
        leading: Icon(icon, color: Theme.of(context).colorScheme.primary),
        title: Text(title),
        subtitle: Text(subtitle),
        trailing: const Icon(Icons.chevron_right),
        onTap: onTap,
      ),
    );
  }

  // Switch 开关卡片
  Widget _buildSwitchCard(
    BuildContext context, {
    required IconData icon,
    required String title,
    required String subtitle,
    required bool value,
    required ValueChanged<bool> onChanged,
  }) {
    return Card(
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
      elevation: 1,
      margin: const EdgeInsets.only(bottom: 12),
      child: ListTile(
        leading: Icon(icon, color: Theme.of(context).colorScheme.primary),
        title: Text(title),
        subtitle: Text(subtitle),
        trailing: Switch(
          value: value,
          onChanged: onChanged,
        ),
      ),
    );
  }

  // 危险操作卡片
  Widget _buildDangerCard(
    BuildContext context, {
    required IconData icon,
    required String title,
    required String subtitle,
    required VoidCallback onTap,
  }) {
    final color = Theme.of(context).colorScheme;
    return Card(
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
      elevation: 1,
      margin: const EdgeInsets.only(bottom: 12),
      child: ListTile(
        leading: Icon(icon, color: color.error),
        title: Text(title, style: TextStyle(color: color.error)),
        subtitle: Text(subtitle),
        trailing: const Icon(Icons.chevron_right),
        onTap: onTap,
      ),
    );
  }

  // 二次确认弹窗
  void _confirmDeleteAccount(BuildContext context) {
    showDialog(
      context: context,
      barrierDismissible: false, // 必须选择操作
      builder: (ctx) => AlertDialog(
        title: Text(AppLocalizations.of(context)!
            .securitySettingsDeleteAccountConfirmTitle),
        content: Text(AppLocalizations.of(context)!
            .securitySettingsDeleteAccountConfirmMsg),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(ctx),
            child: Text(AppLocalizations.of(context)!.commonCancel),
          ),
          FilledButton(
            style: FilledButton.styleFrom(
              backgroundColor: Theme.of(context).colorScheme.error,
            ),
            onPressed: () {
              Navigator.pop(ctx);
              _playExitAnimation(context);
            },
            child: Text(
                AppLocalizations.of(context)!.securitySettingsDeleteAccount),
          ),
        ],
      ),
    );
  }

  // 退出动画
  void _playExitAnimation(BuildContext context) {
    showGeneralDialog(
      context: context,
      barrierDismissible: false,
      barrierLabel: '',
      pageBuilder: (_, __, ___) => const SizedBox.shrink(),
      transitionBuilder: (ctx, anim, __, ___) {
        return FadeTransition(
          opacity: CurvedAnimation(parent: anim, curve: Curves.easeOut),
          child: Container(
            color: Colors.white,
            alignment: Alignment.center,
            child: Text(
              AppLocalizations.of(context)!
                  .securitySettingsDeleteAccountSuccess,
              style: TextStyle(fontSize: 20, color: Colors.red),
            ),
          ),
        );
      },
      transitionDuration: const Duration(seconds: 1),
    ).then((_) {
      Navigator.pop(context); // 返回上一级或首页
    });
  }
}
